import React, { useEffect, useState } from 'react';
import './DepartmentManage.css';
import { Input, Button, Table, message, Modal, Select } from 'antd';
import { DeleteOutlined, FormOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios';


export default function IntegratedManage() {
    const [query, setQuery] = useState('')  // 查询
    const [TipModalOpen, setTipModalOpen] = useState(false)  // 弹窗提示
    const [editModalOpen, setEditModalOpen] = useState(false)  // 编辑弹窗
    const [currentId, setCurrentId] = useState(null)  // 当前点击项id
    const queryChange = (e) => {  // 查询输入框变化
        setQuery(e.target.value)
    }

    const queryBtn = () => {  // 查询按钮
        axios.get('http://8.148.7.123:8000/department/search', {
            params: {
                page: 1,
                size: 100,
                name: query
            }
        }).then(res => {
            setTableData(() => {
                return res.data.data.map(item => {
                    return {
                        ...item,
                        createtime: item.createtime.split('').slice(0, 19).join('').replace('T', ' ')
                    }
                })
            })
        })
    }
    const delChecked = () => {  // 批量删除
        setLoading(true);
        setTimeout(() => {
            axios.get('http://8.148.7.123:8000/department/batchdel', {
                params: {
                    ids: selectedRowKeys
                }
            }).then(res => {
                if (res.data.code === 1) {
                    messageApi.open({
                        type: 'success',
                        content: res.data.msg
                    })
                } else {
                    messageApi.open({
                        type: 'error',
                        content: '删除失败'
                    })
                }
                getTableData();  // 更新表格数据
            })
            setSelectedRowKeys([]);
            setLoading(false);
        }, 1000);
    };
    const handleOk = () => {  // 确认删除
        axios.get('http://8.148.7.123:8000/department/del', {
            params: {
                id: currentId
            }
        }).then(res => {
            if (res.data.code === 1) {
                message.success('删除成功')
                getTableData();  // 更新表格数据
            } else {
                message.error('删除失败')
            }
        })
        setTipModalOpen(false);
    };
    const handleCancel = () => {
        setTipModalOpen(false);
    };
    const del = (id) => {  // 删除按钮
        setCurrentId(id)
        setTipModalOpen(true);
    }

    const edit = (record) => {  // 编辑按钮
        setDepartment(record.name)
        setDoctor(record.maindoctor)
        setCreatetime(record.createtime)
        setDepartmentId(record.id)
        setEditModalOpen(true)
    }

    const editOk = () => {  // 编辑确认
        axios.get('http://8.148.7.123:8000/department/edit', {
            params: {
                id: departmentId,
                name: department,
                maindoctor: doctor,
            }
        }).then(res => {
            if (res.data.code === 1) {
                message.success('修改成功')
                getTableData();  // 更新表格数据
            } else {
                message.error('修改失败')
            }
        })
        setEditModalOpen(false)
    }

    const editCancel = () => {  // 编辑取消
        setEditModalOpen(false)
    }
    // 表格列配置
    const columns = [
        {
            title: '科室编号',
            dataIndex: 'id',
        },
        {
            title: '科室创建时间',
            dataIndex: 'createtime',
        },
        {
            title: '科室名称',
            dataIndex: 'name',
        },
        {
            title: '科室主任',
            dataIndex: 'maindoctor',

        },
        {
            title: '科室操作',
            dataIndex: 'operate',
            render: (text, record) => (
                <div>
                    <DeleteOutlined className='delete_icon' onClick={() => del(record.id)} />
                    <FormOutlined className='edit_icon' onClick={() => edit(record)} />
                </div>
            )
        },

    ];
    const [messageApi, contextHolder] = message.useMessage()  // 弹窗提示
    const [tableData, setTableData] = useState([])  // 表格数据
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);  // 选中项
    const [loading, setLoading] = useState(false);
    const [doctorList, setDoctorList] = useState([]); // 医生列表
    const [department, setDepartment] = useState(null);  // 科室名称
    const [doctor, setDoctor] = useState(null);  // 科室主任
    const [createtime, setCreatetime] = useState('');  // 创建时间
    const [departmentId,setDepartmentId] = useState(null);  // 科室编号

    const departmentChange = (e) => {  // 科室名称变化
        setDepartment(e.target.value);
    };
    const doctorChange = (e) => {  // 科室主任变化
        setDoctor(e);
    }
    const onSelectChange = (newSelectedRowKeys) => {  // 选中项变化时触发
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {  // 行选择器配置
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;  // 是否有选中项
    const getTableData = () => {  // 获取表格数据
        axios.get('http://8.148.7.123:8000/department/list', {
            params: {
                page: 1,
                size: 100,
            }
        }).then(res => {
            setTableData(() => {
                return res.data.data.map(item => {
                    return {
                        ...item,
                        createtime: item.createtime.split('').slice(0, 19).join('').replace('T', ' ')
                    }
                })
            })
        }).catch(err => {
            console.log(err)
        })
    }
    // 获取医生列表
    const getDoctorList = () => {
        axios.get('http://8.148.7.123:8000/doctor/doctornames')
        .then(res => {
            setDoctorList(res.data.data.map(item => {
                return {
                    value: item.name,
                    label: item.name,
                }
            }));
        }).catch(err => {
            console.error(err);
        });
    }
    useEffect(() => {
        getTableData();
        getDoctorList();
    }, [])
    return <div>
        {/* 删除弹框 */}
        <Modal title="系统提示" open={TipModalOpen} onOk={handleOk} onCancel={handleCancel} cancelText='取消' okText='确认删除'>
            <p>您正在进行科室删除操作，此操作不可逆，确定要删除对应科室吗?</p>
        </Modal>
        {/* 编辑弹框 */}
        <Modal title="编辑科室" open={editModalOpen} onOk={editOk} onCancel={editCancel} cancelText='取消' okText='确定'>
            <div className="edit_box">
                <div>
                    <label htmlFor="">科室名称</label>
                    <Input value={department} onChange={departmentChange} style={{ width: '300px' }} />
                </div>
                <div>
                    <label htmlFor="">科室主任</label>
                    <Select placeholder="全部医生" style={{ width: '150px' }}
                        onChange={doctorChange}
                        value={doctor}
                        options={doctorList}
                    />
                </div>
                <div>
                    <label htmlFor="">创建时间</label>
                    <Input disabled value={createtime} style={{ width: '300px' }} />
                </div>
                <div>
                    <label htmlFor="">科室编号</label>
                    <Input disabled value={departmentId} style={{ width: '300px',marginBottom:'30px' }} />
                </div>
            </div>
        </Modal>
        {contextHolder}
        <div className="inp_box">
            <div>
                <label htmlFor="" style={{ fontWeight: 'bold' }}>科室名称</label>
                <Input className="search_inp" value={query} onChange={queryChange} style={{ width: '240px' }} placeholder="请输入科室名称" />
                <Button type="primary" size="small" icon={<SearchOutlined />} onClick={queryBtn}>查询</Button>
            </div>
            <div>
                <Button type="" size="small" onClick={delChecked} disabled={!hasSelected} loading={loading}>删除选中</Button>
            </div>
        </div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={tableData} rowKey={'id'} size='small' />
    </div >
}